<template>
  <div></div>
</template>

<script>
export default {
  data() {
    return {};
  },

  mounted() {
    // 全局监听网络变化
    window.addEventListener("online", () => {
      this.isNetwork = false;
      let that = this;
      let i = 0;

      //来网了（有网的情况下有三次重连的机会）
      //30秒执行一次
      if (typeof WebSocket != "undefined") {
        if (!isconnected) {
          that.webscoketInit();

          setTimeout(() => {
            if (!isconnected) {
              let timerIn = setInterval(() => {
                that.webscoketInit();
                i++;
                if (i == 3) {
                  window.clearInterval(timerIn);
                }
              }, 30000);
            }
          }, 0);
        }
      } else {
        that.$message({
          showClose: true,
          message:
            "您的浏览器不支持Websocket通信协议，请使用Chrome或者Firefox浏览器！",
          type: "warning",
        });
      }
    });

    window.addEventListener("offline", () => {
      //断网了
      this.$message({
        showClose: true,
        message: "网络已断开，正在尝试重连",
        type: "warning",
      });
      this.isNetwork = true;
      console.log(this.ws.readyState, "2222222222222222222222");
      isconnected = false;
      this.ws.close();
    });
  },

  methods: {
    webscoketInit() {
      var timer = -1;
      var ws = new WebSocket(
        `${process.env.VUE_APP_BASE_API_WS}/${this.token}?id=${this.userId}`
      );
      this.ws = ws;
      let that = this;
      // 获取连接状态
      //连接成功建立后响应
      ws.onopen = function () {
        console.log(1111);
        isconnected = true;
        //50秒发送一次心跳
        timer = setInterval(function () {
          var data = { type: "0" };
          ws.send(JSON.stringify(data));
        }, 1000 * 50000);
      };

      // 收到服务器消息后响应;
      ws.onmessage = function (e) {
        let data = JSON.parse(e.data);
        console.log(data, "------------------------------------------接收消息");
        that.concatList.forEach((concatListItem) => {
          // 如果是这个订单才接收
          if (concatListItem.id == data.no) {
            if (data.type == "1") {
              if (data.data.type == "1") {
                // 文字消息
                concatListItem.messages.push({
                  msgUserid: data.data.createBy,
                  createTime: data.data.createTime,
                  createBy: data.data.createBy,
                  msg: data.data.msg,
                  msgid: data.data.id,
                  id: data.data.id,
                });
                console.log(concatListItem.messages, "88888888888888");
                that.getMemberMessage();
                // that.chatMessages.push({});
                // 图片和文件
              } else if (data.data.type == "2") {
                concatListItem.messages.push({
                  myUrl: data.data.msg,
                  createTime: data.data.createTime,
                  createBy: data.data.createBy,
                  msg: data.data.msg,
                  suffix: data.data.msg,
                  orderNo: data.data.no,
                });
                console.log(data, "图片图片图片图片图片图片图片");
                that.getMemberMessage();
                that.$bus.$emit(
                  "historyImFi",
                  data.data.msg,
                  data.data.createBy,
                  data.data.createTime
                );
                // that.uploadImgs.push(that.uploadImgs, data.data.msg);
              } else if (data.data.type == "4") {
                // console.log(data.data);
                let quoteids = data.data.quoteId;
                let msgName = data.data.msg;
                // 得到符合这个id的人（数组）
                let quoteNames = [];
                that.friendArr.forEach((item) => {
                  // console.log(item.userid);
                  if (quoteids.indexOf(item.userId) != -1) {
                    quoteNames.push(item.nickName);
                  }
                });
                console.log(quoteNames); //['下单专用']

                // @某人
                that.quoteName = quoteNames.join();
                concatListItem.messages.push({
                  msgUserid: data.data.createBy,
                  createTime: data.data.createTime,
                  createBy: data.data.createBy,
                  msg: msgName,
                  quoteName: quoteNames.join(),
                  msgid: data.data.id,
                  quoteId: data.data.quoteId,
                });
                that.getMemberMessage();
              } else if (data.data.type == "5") {
                // 邀请某人
              } else if (data.data.type == "6") {
                //@全体成员
              } else if (data.data.type == "7") {
                //URL+回显文本
                console.log(data, "urlurlurlurlurlurlurl");
                // 文字消息
                concatListItem.messages.push({
                  msgUserid: data.data.createBy,
                  createTime: data.data.createTime,
                  createBy: data.data.createBy,
                  msg: data.data.msg,
                  msgid: data.data.id,
                  id: data.data.id,
                  quoteId: data.data.quoteId,
                });
                that.getMemberMessage();
              }
              //如果在当前页面则不提示小红点，如果不在则提示
              that.$bus.$on("sumS", (numw, orderNo) => {
                if (orderNo != concatListItem.id) {
                  that.num = numw;
                }
              });
              // 消息数量;如果是自己则不接受消息
              if (data.data.createBy == that.userId) {
                that.$bus.$emit(
                  "message",
                  data.data.msg,
                  concatListItem.id,
                  0,
                  data.data.createBy
                );
              } else {
                that.num += 1;
                that.$bus.$emit(
                  "message",
                  data.data.msg,
                  concatListItem.id,
                  that.num,
                  data.data.createBy
                );
                // that.readMessage(
                //   data.data.id,
                //   data.data.createBy,
                //   concatListItem.id
                // );
                // 如果两个人都在同一个订单下聊天，那么对方的状态就会一直是已读
                console.log("已读已读已读已读已读已读已读已读");
                let dataRead = {
                  type: "2",
                  no: data.no,
                  msgid: data.data.id, //消息id
                  msgUserid: data.data.createBy, // 发送人的id
                };
                that.ws.send(JSON.stringify(dataRead));
              }
            } else if (data.type == "2") {
              //本人发送的消息，其他人的已读状态
              // console.log("yidudyiduyiduyiduyiduyiduyidu");
              // 通知自己有人阅读了自己发送的消息   修改页面的已读状态
              // console.log(that.chatMessages, "33333333333333333333333333333");
              that.chatMessages.forEach((item) => {
                if (item.id == data.data.id) {
                  item.reads.length += 1;
                  that.$bus.$emit(
                    "message",
                    data.data.msg,
                    concatListItem.id,
                    0,
                    data.data.createBy
                  );
                }
              });
            } else if (data.type == "3") {
              //消息撤回
              concatListItem.messages.push({
                orderNo: data.data.no,
                msg: "消息已撤回",
                msgid: data.data.msgid,
              });
            } else if (data.type == "0") {
              console.log("555555555");
            }
          } else {
            return;
          }
        });
      };
      //连接关闭后响应
      ws.onclose = function (e) {
        isconnected = false;
        // ;
        window.clearInterval(timer);
        timer = -1;
        console.log(
          "websocket 断开: " + e.code + " " + e.reason + " " + e.wasClean
        );

        if (navigator.onLine) {
          //有网络
          let i = 0;
          //来网了（有网的情况下有三次重连的机会） //30秒执行一次
          if (!isconnected) {
            that.webscoketInit();
            setTimeout(() => {
              if (!isconnected) {
                let timerCl = setInterval(() => {
                  that.webscoketInit();
                  console.log("websocket连接");
                  i++;
                  if (i == 3) {
                    window.clearInterval(timerCl);
                  }
                }, 30000);
              }
            }, 0);
          }
        } else {
          //无网络
          that.$message({
            showClose: true,
            message: "网络已断开，正在尝试重连",
            type: "warning",
          });
        }
      };
    },
    // 发送消息

    sendMsg() {
      //  做判断防止发送空格
      if (!this.content) {
        return;
      }
      var time = new Date().toLocaleString();
      //type 0 心跳（120秒没有读写操作会关闭通道，要写个定时器定时发送心跳） 1 发送消息 2 消息已读 3 消息撤回
      let data = {
        type: "1",
        msgType: this.msgType,
        no: this.currentChat.orderNo,
        msg: this.content,
        msgid: this.tempSnowflake.nextId() + "",
        createBy: this.userId,
        msgUserid: this.userId,
        createTime: time,
        myUrl: this.myUrl,
        quoteid: this.quoteId.join(","),
      }; //no 订单号 msg 消息本体 msgid 生成的雪花算法id
      // var data = { "type": "2", "no": "123456", "msgid": "123456789", "msgUserid": "1" }//no 订单号  消息id msgUserid 发送该消息的用户id
      // var data = { "type": "3", "no": "123456", "msgid": "123456789" }//no 订单号 msgid 消息id
      this.quoteId = [];
      console.log(data, "-------------------------------------------发送消息");
      if (navigator.onLine && isconnected) {
        this.ws.send(JSON.stringify(data));
        // this.$bus.$emit("message", this.content);
        console.log(this.content);
        this.$bus.$emit("historys", data);
        // // 发送消息，自己的数量不变
        this.$bus.$emit(
          "message",
          this.content,
          this.currentChat.orderNo,
          0,
          this.userId
        );
        // 清空输入框
        this.content = "";
      } else {
        this.$message({
          showClose: true,
          message: "您的网络已断开",
          type: "warning",
        });
      }
    },
  },
};
</script>

<style></style>
